package cn.itsource.user.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.basic.util.VerifyCodeUtils;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IVerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeService implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Override
    public AjaxResult imageCode(String key) {
        //调用工具类随机生成4位图片验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //存入Redis，key为验证码的key，value为验证码
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        //调用工具类将图形验证码编码成Base64的字符串
        String base64 = VerifyCodeUtils.verifyCode(115, 40, code);
        //将编码后的验证码返回给前端
        return new AjaxResult().me().setResultObj(base64);
    }

    @Override
    public AjaxResult smsCode(Map<String, String> map) {
        /**
         * 校验
         */
        //校验空值
        String phone = map.get("phone");
        String imageCode = map.get("imageCode");
        String imageCodeKey = map.get("imageCodeKey");
        if (phone==null){
            throw new RuntimeException("手机号不能为空");
        }
        if (imageCode==null){
            throw new RuntimeException("图片验证码不能为空");
        }
        Object obj = redisTemplate.opsForValue().get(imageCodeKey);
        //校验图形验证码是否过期
        if (obj==null){
            throw new RuntimeException("图片验证码已过期");
        }
        //校验图形验证码是否错误
        if (!obj.toString().equalsIgnoreCase(imageCode)){
            throw new RuntimeException("图片验证码错误");
        }
        //验证当前手机是否已经被注册
        User user = userMapper.selectByPhone(phone);
        if(user!=null){
            throw new RuntimeException("手机号已被注册");
        }
        /**
         * 获取短信验证码
         */
        //获取redis中的短信验证码
        Object smsCodeObj = redisTemplate.opsForValue().get("register" + phone);
        String code = null;
        //如果redis中没有短信验证码或者已经过期，则生成
        if (smsCodeObj==null){
            code = StrUtils.getRandomString(4);
        }else {
            //判断重发时间
            long oldTime = Long.parseLong(smsCodeObj.toString().split(":")[1]);
            //判断是否在60s内
            if (System.currentTimeMillis()-oldTime<=1*60*1000){
                throw new RuntimeException("操作频繁，稍后重试");
            } else {
                //60s后则设置验证码为前一次的验证码
                code = smsCodeObj.toString().split(":")[0];
            }
        }

        //保存到redis，key为"register:手机号"，value为"验证码:时间戳"
        redisTemplate.opsForValue().set("register:"+phone,code+":"+System.currentTimeMillis(),5,TimeUnit.MINUTES);

        //调用攻击类发送短信验证码     这里模拟为输出到控制台代替

        System.out.println("短信验证码："+code);

        return new AjaxResult().me().setResultObj(code);
    }

    @Override
    public AjaxResult binderSmsCode(Map<String, String> map) {
        /**
         * 校验
         */
        //校验空值
        String phone = map.get("phone");
        if (phone==null){
            throw new RuntimeException("手机号不能为空");
        }
        /**
         * 获取短信验证码
         */
        //获取redis中的短信验证码
        Object smsCodeObj = redisTemplate.opsForValue().get("binder:" + phone);
        String code = null;
        //如果redis中没有短信验证码或者已经过期，则生成
        if (smsCodeObj==null){
            code = StrUtils.getRandomString(4);
        }else {
            //判断重发时间
            long oldTime = Long.parseLong(smsCodeObj.toString().split(":")[1]);
            //判断是否在60s内
            if (System.currentTimeMillis()-oldTime<=1*60*1000){
                throw new RuntimeException("操作频繁，稍后重试");
            } else {
                //60s后则设置验证码为前一次的验证码
                code = smsCodeObj.toString().split(":")[0];
            }
        }

        //保存到redis，key为"register:手机号"，value为"验证码:时间戳"
        redisTemplate.opsForValue().set("binder:"+phone,code+":"+System.currentTimeMillis(),5,TimeUnit.MINUTES);

        //调用攻击类发送短信验证码     这里模拟为输出到控制台代替

        System.out.println("短信验证码："+code);

        return new AjaxResult().me().setResultObj(code);
    }
}
